package com.example.cmpe277stockdata.RSSFeeds;

import java.net.URL;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathFactory;

import org.w3c.dom.CharacterData;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

import com.example.cmpe277stockdata.beans.RealTimeBean;
import com.example.cmpe277stockdata.constants.DataConstants;
import com.example.cmpe277stockdata.exceptions.ServiceUnavailableException;

public class RealTimeRSSFeed 
{

	public RealTimeBean getRealTimeRate(String ticker,String company)  throws ServiceUnavailableException
	{
		RealTimeBean realTime = new RealTimeBean();
		try 
		{
			String URLString = DataConstants.REAL_RSS_FEED + ticker;
			DocumentBuilder builder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
			URL u = new URL(URLString);
			Document doc = builder.parse(u.openStream());
			NodeList nodes = doc.getElementsByTagName("item");
		
			for(int i=0;i<nodes.getLength();i++) 
			{
				Element element = (Element)nodes.item(i);	
				int innersize = element.getElementsByTagName("description").getLength();
			    for(int j=0;j<innersize;j++)
			    {
				    XPath xPath = XPathFactory.newInstance().newXPath();
				    String value = xPath.evaluate("//item/description/text()", doc).trim();
				    value = value.replaceAll("<!--.*?-->", "").replaceAll("<[^>]+>", "");
				    String[] finalarray = value.split("&nbsp;");
				    
				    String stockValue = finalarray[2].substring(5, finalarray[2].length()).trim();
				    String change = finalarray[3].substring(7, finalarray[3].length()).trim();
				    String percChange = finalarray[5].substring(8, finalarray[5].length()).trim();
				    String volume =finalarray[7].substring(7,finalarray[7].length()).trim() + " " + finalarray[8].trim();
				    
				    realTime.setCompany(company);
				    realTime.setTickerSymbol(ticker);
				    double stockData = 0;
				    try
				    {
				    	stockData = Double.parseDouble(stockValue);
				    }
				    catch(Exception e)
				    {
				    }
				    realTime.setStockValue(stockData);
				    double changeValue = 0;
				    try
				    {
				    	changeValue= Double.parseDouble(change);
				    }
				    catch(Exception e)
				    {
				    }
				    realTime.setChange(changeValue);
				    realTime.setPercentageChange(percChange);
				    int vol = 0;
				    try
				    {
				    	vol = Integer.parseInt(volume.replaceAll(",", "").trim());
				    }
				    catch(Exception e)
				    {
				    }
				    realTime.setVolume(vol);
		    	}
			}
		}
		catch(Exception ex) 
		{
			System.out.println("Exception occured in RSSReader layer: " + ex.getMessage());
			throw new ServiceUnavailableException();
		}
	return realTime;
	}
	
	protected float getFloat(String value) 
	{
		if(value != null && !value.equals("")) 
		{
		return Float.parseFloat(value);
		}
		return 0;
		}

		private String getCharacterDataFromElement(Element e)
		{
		try 
		{
		Node child = e.getFirstChild();
		if(child instanceof CharacterData) {
		CharacterData cd = (CharacterData) child;
		return cd.getData();
		}
		}
		catch(Exception ex) 
		{
			ex.getMessage();
		}
		return "";
		} 

		protected String getElementValue(Element parent,String label) 
		{
			return getCharacterDataFromElement((Element)parent.getElementsByTagName(label).item(0));
		}
		
		public static void main(String args[])
		{
			RealTimeRSSFeed read= new RealTimeRSSFeed();
			
			for(int i=0;i< ResultClass.tickerarray.length;i++)
			{
				String[] tickerexpansion = ResultClass.tickerarray[i].split(":");
				try
				{
					read.getRealTimeRate(tickerexpansion[0],tickerexpansion[1]);
				}
				catch(Exception e)
				{
				
				}
			}

		}
}
